
const MediaModel = require('../models/media-model')
const MediaSeasonModel = require('../models/media-season-model')
const TMDB = require('../utils/media-netdata/tmdb');


const outdated = 1000 * 60 * 60 * 24 * 1; // 1 days

const getMedia = async (tmdbid, type, update) => {
    let media = await MediaModel.getByTmdbid(tmdbid)
    update = update || ( media ? ((new Date().getTime() - media.syncTime) > outdated ) : true )
    if (!media || update) {
        let info;
        if (type === 'movie') {
            info = await TMDB.movieDetail(tmdbid);
        } else if (type === 'tv') {
            info = await TMDB.tvDetail(tmdbid);
        }
        if (info) {
            if (media) {
                media.info = JSON.stringify(info);
                media.syncTime = new Date();
                await MediaModel.updateBy({
                    info: media.info,
                    syncTime: media.syncTime
                }, {id:media.id})
            } else {
                media = {
                    tmdbid: info.id,
                    info: JSON.stringify(info),
                    type: type,
                    syncTime: new Date()
                }
                await MediaModel.insert(media)
            }
        }
    }
    return media
}
const getMediaSeason = async (tmdbid, season, update) => {
    let mediaSeason = await MediaSeasonModel.getByTmdbidSeason(tmdbid, season)
    update = update || ( mediaSeason ? ((new Date().getTime() - mediaSeason.syncTime) > outdated ) : true )
    if (!mediaSeason || update) {
        const info = await TMDB.tvSeason(tmdbid, season);
        if (info) {
            if (mediaSeason) {
                mediaSeason.info = JSON.stringify(info);
                mediaSeason.syncTime = new Date();
                await MediaSeasonModel.updateBy({
                    info: mediaSeason.info,
                    syncTime: mediaSeason.syncTime
                }, {id:mediaSeason.id})
            } else {
                mediaSeason = {
                    tmdbid: tmdbid,
                    season: season,
                    info: JSON.stringify(info),
                    syncTime: new Date()
                }
                await MediaSeasonModel.insert(mediaSeason)
            }
        }
    }
    return mediaSeason
}


const deleteMedia = async (tmdbid) => {
    await MediaModel.delete({tmdbid})
    await MediaSeasonModel.delete({tmdbid})
}

module.exports = {
    getMedia, getMediaSeason, deleteMedia
}